<template>
  <el-dialog title="新增退货单" :close-on-click-modal="false" :visible.sync="visible" center fullscreen>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="120px">
      <el-row>
        <el-col :span="8" v-if="this.dataForm.id">
          <el-form-item label="单据编号" prop="returnBillId">
            <el-input v-model="dataForm.returnBillId" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入库类型">
            <el-input value="采购退货单" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期" prop="createTime">
            <el-input :value="this.nowDate" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="制造商" prop="supplyName">
            <el-input v-model="dataForm.supplyName" readonly :disabled="this.disabledFlag">
              <el-button slot="append" @click="checkSupplyList" :disabled="this.disabledFlag">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发出仓位" prop="outStockId">
            <el-select v-model="dataForm.outStockId" placeholder="请选择" :disabled="this.disabledFlag">
              <el-option
                v-for="item in outStockOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单人" prop="createUsername">
            <el-input v-model="dataForm.createUsername" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="运单号" prop="transportId">
            <el-input v-model="dataForm.transportId"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="memo">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="dataForm.memo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form :inline="true">
      <el-form-item>
        <el-button type="primary" @click="addGoodsBySingle">单品添加商品</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="barcodeScan()">条码扫描</el-button>
      </el-form-item>
      <el-form-item style="float: right;">
        <el-button type="danger" @click="delTableData">删除</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="handleSelectionChange" show-summary  :summary-method="getSummaries">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column prop="code" label="商品代码" width="130"></el-table-column>
      <el-table-column prop="viewGoodsName" label="商品名称" min-width="240"></el-table-column>
      <el-table-column prop="spec" label="型号" width="80"></el-table-column>
      <el-table-column prop="unitType" label="计量单位" :formatter="unitTypeFormatter" width="60">

      </el-table-column>
      <el-table-column prop="goodsQuantity" label="可用库存" width="60"></el-table-column>
      <el-table-column prop="number" label="数量" width="230">
        <template slot-scope="scope">
          <el-form :model="scope.row" :rules="dataListRule" ref="inputForm">
            <el-form-item prop="number">
              <el-input v-show="true" v-model="scope.row.number" placeholder="数量" :ref="'number'+scope.$index" @keyup.enter.native="numberChange(scope.$index)"/>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="barcode" label="商品条码" width="170"></el-table-column>
      <el-table-column prop="batch" label="批次" width="120">
        <template slot-scope="scope">
          <el-form :model="scope.row" :rules="dataListRule" ref="inputForm">
            <el-form-item prop="batch">
              <el-input v-show="true" v-model="scope.row.batch" placeholder="批次" :ref="'batch'+scope.$index" v-if="(scope.row.ctgId == 4)|| (scope.row.ctgId == 5)" />
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保存</el-button>
    </span>
    <supply-search v-if="supplySearchVisible" ref="supplySearch" @refreshData="renewFormData"></supply-search>
    <goods-list v-if="goodsListVisible" ref="sinleGoodsList" @updateForm="updateFormData"></goods-list>
    <barcode-scan v-if="barcodeVisible" ref="barcodeDialog" @refreshData="getBarcodeGoodsData"></barcode-scan>
  </el-dialog>
</template>

<script>
import { filterParams } from "@/util/tools"
import { getStockList } from "@/api/eims/stock"
import {
  returnManagementById,
  saveNewReturnManagementOrder,
  putReturnManagementObj
} from "@/api/eims/return-management"
import { fetchCtgList } from "@/api/eims/goods"
import GoodsList from "./goods-search-single"
import SupplySearch from "@/components/business/SearchSupply"
import { mapGetters } from "vuex"

import BarcodeScan from '@/components/business/BarcodeScan'
export default {
  data() {
    var checkNumber = (rule, value, callback) => {
      let reg = /^[1-9][0-9]*$/g;
      if (value === "") {
        callback(new Error("请输入内容"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确的值"));
      } else {
        callback();
      }
    };
    var checkBatch = (rule, value, callback) => {
      let reg = /^[a-zA-Z0-9]+$/g;
      if(value === "") {
        callback(new Error("请输入内容"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确的值"));
      } else {
        callback();
      }
    };
    return {
      ischeck: false,
      nowTime: "",
      nowDate: "",
      visible: false,
      dataForm: {
        id: 0,
        applyStatus: "0",
        goodsId: "",
        goodsName: "",
        supplyId: "",
        supplyName: "",
        memo: "",
        goodsInfos: [],
        deptId: "",
        batch: ''
      },
      goodsOptions: [],
      dataList: [],
      outStockOptions: [],
      dataListLoading: false,
      dataRule: {
        supplyName: [
          { required: true, message: "请选择制造商", trigger: "blur" }
        ],
        outStockId: [{ required: true, message: "请选择发出仓库", trigger: "blur" }],
      },
      dataListRule: {
        number: [
          {required: true, message: '请输入数量', trigger: 'blur'},
          {validator:checkNumber,trigger: "blur" }
        ],
        batch: [
          {required: true, message: '请输入批次', trigger: 'blur'},
          {validator:checkBatch,trigger: "blur" }
        ]
      },
      supplySearchVisible: false,
      goodsListVisible: false,
      barcodeVisible: false,
      selectionList: [],
      disabledFlag: false
    };
  },
  components: {
    GoodsList,
    SupplySearch,
    BarcodeScan
  },
  created() {
    this.timeFormate(new Date());
  },
  computed: {
      ...mapGetters(["userInfo"])
    },
  methods: {
    init(id) {
      this.disabledFlag = false
      for (let key in this.dataForm) {
        if (key != "applyStatus" || key != "returnBillId") {
          this.dataForm[key] = ""
        }
      }
      this.dataForm.id = id || 0
      if (this.dataForm.id != 0) {
        this.disabledFlag = true
      }
      this.dataForm.createUsername = this.userInfo.realName
      this.dataForm.supplyId = ""
      this.getOutStockList()
      this.dataForm.applyStatus = "0"
      this.visible = true
      this.dataList = []
      this.dataForm.goodsInfos = []
      if (this.dataForm.id) {
        this.dataListLoading = true
        returnManagementById(this.dataForm.id).then(response => {
          if(response.data.code == '0'){
            this.dataForm = response.data.data
            this.dataList = response.data.data.goodsInfos
            this.dataList.forEach(item => {
              item.goodsQuantity = item.quantity
            })
          }else{
            this.$message.error(response.data.msg)
          }
          this.dataListLoading = false
        })
      }
    },
    numberChange(index){
      this.$refs['number'+(index*1 + 1)].focus()
    },
    // 出仓选择
    stockNameChange($event) {
      this.outStockOptions.forEach(item => {
        if (item.value == $event) {
          this.dataForm.outStockName = item.label
        }
      })
    },
    // 获取仓位列表
    getOutStockList() {
      getStockList().then(response => {
        if(response.data.code == '0'){
          this.outStockOptions = response.data.data;
        }else{
          this.$message.error(response.data.msg)
        }
      })
    },
    // 商品类别改变时获取名字
    goodsSelectChange($event) {
      this.goodsOptions.forEach(item => {
        if (item.value == $event) {
          this.dataForm.goodsName = item.name
        }
      })
    },
    checkSupplyList() {
      let data = {}
      this.supplySearchVisible = true
      this.$nextTick(() => {
        this.$refs.supplySearch.init(data)
      })
    },
    // 选择制造商
    renewFormData(data) {
      this.dataForm.supplyId = data.id
      this.dataForm.supplyName = data.name
    },
    // 打开商品列表弹窗
    addGoodsBySingle() {
      // 判断是否选中制造商
      if (!this.dataForm.supplyId) {
        this.$message.warning("请选择制造商")
        return
      }
      if (!this.dataForm.outStockId) {
        this.$message.warning("请选择发出仓位")
        return
      }
      let params = {
        supplyId: this.dataForm.supplyId,
        supplyName: this.dataForm.supplyName,
        stockId: this.dataForm.outStockId
      }
      let data = { params: params, data: this.dataList }
      this.goodsListVisible = true
      this.$nextTick(() => {
        this.$refs.sinleGoodsList.init(data)
      })
    },
    handleSelectionChange(val) {
      this.selectionList = val
    },
    // 删除选中的商品
    delTableData () {
      this.selectionList.forEach((item,index) => {
        for(let i = 0; i < this.dataList.length; i++){
          if(this.dataList[i] == item){
            this.dataList.splice(i,1)
            this.dataForm.goodsInfos.splice(i,1)
          }
        }
        this.selectionList = []
      })
    },
    //更新表单数据
    updateFormData(data) {
      this.dataList = JSON.parse(JSON.stringify(data))
      let list = []
      data.forEach(item => {
        list.push(item)
      })
      this.dataForm.goodsInfos = list
    },
    //  条码扫描
    barcodeScan() {
      this.barcodeVisible = true
      this.$nextTick(() => {
        this.$refs.barcodeDialog.init(this.dataForm.outStockId)
      })
    },
    //  条码扫描获取的数据
    getBarcodeGoodsData(data) {
      let obj = {...data}
      obj.goodsId = obj.id
      let result = this.dataForm.goodsInfos.some(item => {
        return item.goodsBarcode == obj.goodsBarcode
      })
      if(result){
        this.dataForm.goodsInfos.forEach(item => {
          if(item.goodsBarcode == obj.goodsBarcode){
            item.allocationQuantity += 1
          }
        })
      }else{
        this.dataList.push(obj)
        this.dataForm.goodsInfos.push(obj)
      }
    },
    // 表单提交
    dataFormSubmit() {
      if (this.dataList.length <= 0) {
        this.$message.warning("请选择退货商品")
        return
      }
      for(var i = 0 ;i<this.dataList.length ; i++){
        let reg1= /^[1-9][0-9]*$/g
        if(!reg1.test(this.dataList[i].number)){
          this.$message.warning("输入的数量格式有误")
          return
        }
        if(this.dataList[i].number > this.dataList[i].goodsQuantity){
          this.$refs['number'+i].focus()
          this.$message.warning("输入的数量大于库存数量,请重新输入")
          return
        }
        if(this.dataList[i].ctgId == 4 || this.dataList[i].ctgId == 5){
          let reg = /^[a-z0-9A-Z]+$/g
          //判断该字段是否未定义
          if(typeof this.dataList[i].batch == 'undefined'){
            this.$message.warning("请输入批次")
            return
          }
          if(!reg.test(this.dataList[i].batch)){
            this.$refs['batch'+i].focus()
            this.$message.warning("输入的批次格式有误")
            return
          }
        }
      }
      this.ischeck = true
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.dataList.forEach((item, index) => {
            this.dataForm.goodsInfos[index].number = item.number
            this.dataForm.goodsInfos[index].memo = item.memo
          })
          this.dataForm.goodsInfos.forEach(item => {
            item = filterParams(item)
          })
          if (this.dataForm.id) {
            putReturnManagementObj(this.dataForm).then(response => {
              if(response.data.code == '0'){
                this.$message.success("修改成功")
                this.visible = false
                this.$emit("refreshDataList")
              }else{
                this.$message.error(response.data.msg)
              }
              this.ischeck = false
            }).catch(() => {
              this.ischeck = false
            })
          } else {
            saveNewReturnManagementOrder(this.dataForm).then(response => {
              if(response.data.code == '0'){
                this.$message.success("保存成功")
                this.visible = false
                this.$emit("refreshDataList")
              }else{
                this.$message.error(response.data.msg)
              }
              this.ischeck = false
            }).catch(() => {
              this.ischeck = false
            })
          }
        } else {
          this.ischeck = false
          return false;
        }
      });
    },
    //  合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          if(index == 5 || index == 6){
            sums[index] = '合计： ' + values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0)
          }
        }
      });
      return sums;
    },
    //显示当前时间（年月日时分秒）
    timeFormate(timeStamp) {
      let year = new Date(timeStamp).getFullYear();
      let month =
        new Date(timeStamp).getMonth() + 1 < 10
          ? "0" + (new Date(timeStamp).getMonth() + 1)
          : new Date(timeStamp).getMonth() + 1;
      let date =
        new Date(timeStamp).getDate() < 10
          ? "0" + new Date(timeStamp).getDate()
          : new Date(timeStamp).getDate();
      let hh =
        new Date(timeStamp).getHours() < 10
          ? "0" + new Date(timeStamp).getHours()
          : new Date(timeStamp).getHours();
      let mm =
        new Date(timeStamp).getMinutes() < 10
          ? "0" + new Date(timeStamp).getMinutes()
          : new Date(timeStamp).getMinutes();
      let ss =
        new Date(timeStamp).getSeconds() < 10
          ? "0" + new Date(timeStamp).getSeconds()
          : new Date(timeStamp).getSeconds();
      this.nowTime =
        "POUT" +
        year +
        "" +
        month +
        "" +
        date +
        "" +
        hh +
        "" +
        mm +
        "" +
        ss +
        this.dataForm.deptId;
      this.nowDate = year + "-" + month + "-" + date;
    },
    unitTypeFormatter(row, column, cellValue, index) {
        switch (cellValue) {
          case '01':
            return '片'
            break;
          case '02':
            return '盒'
            break;
          case '03':
            return '副'
            break;
          case '04':
            return '瓶'
            break;
          case '05':
            return '张'
            break;
          case '06':
            return '把'
            break;
          case '07':
            return '个'
            break;
          case '08':
            return '只'
            break;
          case '09':
            return '套'
            break;
          case '10':
            return '天'
            break;
          case '11':
            return '包'
            break;
        }
      }
  }
};
</script>

<style lang="scss" scoped>
  /deep/ .el-table {
  display: flex;
  flex-direction: column;
  }

  /deep/ .el-table__body-wrapper {
  order: 1;
  }
  /deep/ .bgChange {
    color: red!important;
  }
</style>
